package org.javaweb.cms_web.controller;

import org.javaweb.cms_web.model.Enum.UserStatus;
import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.service.UserService;
import org.javaweb.cms_web.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

@Controller
public class TeamMemberInfoController {

    @Resource
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @GetMapping("/team-member/info")
    public String info(Model model) {
        User user = hostHolder.getUser();

        if (user == null) {
            return "redirect:/login";
        }

        if (user.getStatus() == UserStatus.TEAM_NOT_PASSED.getCode()) {
            String auditInfo = user.getAuditInfo();
            model.addAttribute("message", "修改未通过，请重新输入个人信息" + "\n不通过的理由:" + auditInfo);
            model.addAttribute("messageType", "error");

            user.setStatus(UserStatus.TEAM_PENDING_REVIEW.getCode());
            userService.updateUser(user);

            return "teammember-info";  // 跳转到编辑个人信息的页面
        }

        model.addAttribute("user", user);
        return "teammember-info";
    }

    @PostMapping("/team-member/info")
    public String update(@RequestParam String nickname,
                         @RequestParam String name,
                         @RequestParam String email,
                         @RequestParam String phoneNumber,
                         @RequestParam String researchDirection,
                         @RequestParam String academicBackground,
                         @RequestParam String researchAchievements,
                         Model model) {

        User user = hostHolder.getUser();

        if (user != null) {
            user.setNickname(nickname);
            user.setName(name);
            user.setEmail(email);
            user.setPhoneNumber(phoneNumber);
            user.setResearchDirection(researchDirection);
            user.setAcademicBackground(academicBackground);
            user.setResearchAchievements(researchAchievements);
            user.setStatus(UserStatus.TEAM_PENDING_REVIEW.getCode());
            user.setTeamId(1);
            userService.updateUser(user);

            model.addAttribute("message", "信息已提交审核");
            model.addAttribute("messageType", "success");

            model.addAttribute("user", user);
        }

        return "teammember-info";

    }
}
